<!--
 * @页面名称:门类报表
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="form-tab6">
    <!-- 按钮组 -->
    <div class="button-group">
      <el-row>
        <el-col :span="6">
          <el-tooltip class="box-item" placement="bottom-end">
            <template #content>
              <span>添加模板</span>
            </template>
            <el-button :disabled="BtnStatus[0]" icon="FolderAdd" @click="add"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" placement="bottom-end">
            <template #content>
              <span>修改模板</span>
            </template>
            <el-button :disabled="BtnStatus[1]" icon="Edit" @click="edit"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" placement="bottom-end">
            <template #content>
              <span>删除模板</span>
            </template>
            <el-button :disabled="BtnStatus[2]" icon="Delete" @click="del"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" placement="bottom-end">
            <template #content>
              <span>下载模板</span>
            </template>
            <el-button :disabled="BtnStatus[3]" icon="Upload" @click="download"></el-button>
          </el-tooltip>
        </el-col>
      </el-row>
    </div>
    <!-- 表格模块 -->
    <stable
      style="height: 100%"
      :columns="tableSetting.columns"
      :data="tableSetting.data"
      @rowClick="rowClick"
      @selectionChange="selection"
    ></stable>
    <!-- 新增修改哦弹出框 -->
    <modal v-model:visible="modalSetting.visible" :title="modalSetting.title" width="500" draggable @ok="handleOK(formRef)">
      <el-form label-width="100px" :model="formData" :rules="rules" ref="formRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板文件:">
              <el-upload v-model:file-list="fileList" multiple :auto-upload="false" :on-change="uploadChange">
                <el-button icon="Upload">选择文件</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有效:" prop="RM_Enabled">
              <el-checkbox v-model="formData.RM_Enabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="报表名称:" prop="RM_FileName">
          <el-input v-model="formData.RM_FileName"></el-input>
        </el-form-item>
        <el-form-item label="顺序号:" prop="RM_Index">
          <el-input type="number" v-model="formData.RM_Index"></el-input>
        </el-form-item>
        <el-divider />
        <el-row>
          <el-col :span="12">
            <el-form-item label="每页行数:" prop="Rows">
              <el-input v-model="formData.Rows"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每页列数:" prop="Columns">
              <el-input v-model="formData.Columns"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否分页:" prop="IsPaging">
              <el-checkbox v-model="formData.IsPaging"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="空行补齐:" prop="IsBlankLine">
              <el-checkbox v-model="formData.IsBlankLine"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否拆分:" prop="Resolve">
              <el-checkbox v-model="formData.Resolve"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否垂直分组:" prop="VerticalGroup">
              <el-checkbox v-model="formData.VerticalGroup"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否前端报表:" prop="RM_IsFront">
              <el-checkbox v-model="formData.RM_IsFront"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="拆分字段:" prop="ResolveContext">
          <el-input v-model="formData.ResolveContext"></el-input>
        </el-form-item>
        <el-form-item label="遍历顺序:" prop="Orientation">
          <el-select v-model="formData.Orientation" placeholder="请选择">
            <el-option label="Horizontal" value="1"></el-option>
            <el-option label="Vertical" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-divider>报表参数</el-divider>
        <el-form-item label="数据源:" prop="DataSource">
          <el-select v-model="formData.DataSource" placeholder="请选择">
            <!-- <el-option v-for="(item, index) in tableList" :key="index" :label="item.FMT_Name" :value="item.FMT_Name"></el-option> -->
            <el-option label="本表父级" value="本表父级"></el-option>
            <el-option label="本表" value="本表"></el-option>
            <el-option label="本表子级" value="本表子级"></el-option>
            <el-option label="分类目录" value="分类目录"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子级表名:" prop="TableName">
          <el-input v-model="formData.TableName"></el-input>
        </el-form-item>
        <el-form-item label="OrderBy:" prop="OrderBy">
          <el-input v-model="formData.OrderBy"></el-input>
        </el-form-item>
        <el-form-item label="SQL:" prop="SQL">
          <el-input v-model="formData.SQL"></el-input>
        </el-form-item>
      </el-form>
    </modal>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import { fileToBase64, base64ToBlob, base64ToBuffer, arrayToBase64, isBase64 } from "@/utils/util";
import { fileSizeFormat, timeFormat } from "@/utils/formatter";
import { saveAs } from "file-saver";
import useCurrentInstance from "@/utils/useCurrentInstance";

const props = defineProps({
  tableList: {
    type: Array as any,
    default: () => {
      return [];
    }
  }
});
const { proxy } = useCurrentInstance();
// 按钮状态
const BtnStatus = ref([true, true, true, true]);
// 表格配置
const tableSetting = reactive({
  columns: [
    { type: "checkbox", width: 60 },
    { title: "序号", field: "RM_Index", width: 90, sortable: true },
    { title: "报表名称", field: "RM_FileName", sortable: true, width: 120 },
    { title: "日期", field: "RM_FileTime", sortable: true, width: 120, formatter: timeFormat },
    {
      title: "是否有效",
      field: "RM_Enabled",
      sortable: true,
      width: 120,
      slots: {
        default: ({ row }: any) => {
          return [<el-checkbox disabled v-model={row.RM_Enabled} />];
        }
      }
    },
    { title: "文件大小", field: "RM_FileSize", sortable: true, width: 120, formatter: fileSizeFormat },
    { title: "参数", field: "RM_Config", sortable: true }
  ],
  data: [],
  rowClickObj: {} as any,
  selectData: [] as any[]
});
// 弹出框配置
const modalSetting = reactive({
  type: 1,
  title: "新增",
  visible: false
});
// 表单绑定字段
const formData = ref({
  RM_Enabled: false,
  RM_FileName: "",
  RM_FileSize: "",
  RM_Index: 1,
  RM_Entity: "",
  Rows: 1,
  Columns: 1,
  RM_IsFront: true,
  IsPaging: false,
  IsBlankLine: false,
  Resolve: false,
  VerticalGroup: false,
  ResolveContext: "",
  Orientation: "",
  DataSource: "",
  TableName: "",
  OrderBy: "",
  SQL: ""
});
// 表单实例
const formRef = ref();
// 表单验证规则
const rules = reactive({
  RM_Index: [{ required: true, message: "请输入顺序号", trigger: "blur" }]
});
// 文件上传列表
const fileList = ref([]);
// 父级行数据
const parentData = ref<any>({});
// 获取报表数据
const getTableData = (record?: any) => {
  if (!record) {
    return;
  }
  parentData.value = record;
  proxy.$vueAxios
    .post("Master_Base_ReportModule/GetConditional", {
      order: "rM_Index asc",
      dtoList: [{ fieldName: "FMT_ID", fieldValue: record.FMT_ID }]
    })
    .then((res: any) => {
      if (res.Mark) {
        BtnStatus.value[0] = false;
        tableSetting.data = res.List;
      }
    });
};
// 表格单击事件
const rowClick = ({ row }: any) => {
  tableSetting.rowClickObj = row;
  BtnStatus.value[1] = false;
  BtnStatus.value[3] = false;
};
// 表格多选
const selection = (val: any[]) => {
  tableSetting.selectData = val;
  BtnStatus.value[2] = false;
};
// 新增
const add = () => {
  modalSetting.type = 1;
  modalSetting.title = "新增";
  modalSetting.visible = true;
  formData.value.RM_Index = tableSetting.data.length + 1;
  fileList.value = [];
  formRef.value?.resetFields();
};
// 修改
const edit = () => {
  modalSetting.type = 2;
  modalSetting.visible = true;
  modalSetting.title = "修改";
  fileList.value = [];
  const tempConfig = JSON.parse(tableSetting.rowClickObj.RM_Config);
  nextTick(() => {
    formData.value = {
      ...tempConfig,
      RM_Enabled: tableSetting.rowClickObj.RM_Enabled,
      RM_FileName: tableSetting.rowClickObj.RM_FileName,
      RM_Index: tableSetting.rowClickObj.RM_Index,
      RM_FileSize: tableSetting.rowClickObj.RM_FileSize,
      RM_Entity: tableSetting.rowClickObj.RM_Entity,
      RM_IsFront: tableSetting.rowClickObj.RM_IsFront,
      IsBlankLine: tempConfig.IsBlankLine === 1 ? true : false,
      IsPaging: tempConfig.IsPaging === 1 ? true : false,
      Resolve: tempConfig.Resolve === 1 ? true : false,
      VerticalGroup: tempConfig.VerticalGroup === 1 ? true : false
    };
    console.log(formData.value);
  });
  formRef.value?.resetFields();
};
// 删除
const del = () => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios
        .post(
          "Master_Base_ReportModule/delete",
          tableSetting.selectData.map(v => v.RM_ID)
        )
        .then((res: any) => {
          if (res.Mark) {
            tableSetting.data = tableSetting.data.filter(
              (v: any) => !tableSetting.selectData.some((j: any) => j.RM_ID === v.RM_ID)
            );
            proxy.$message.success("删除成功");
          } else {
            proxy.$message.error("删除失败");
          }
        });
    })
    .catch(err => {
      proxy.$message("取消删除");
    });
};
// 下载
const download = () => {
  if (isBase64(tableSetting.rowClickObj.RM_Entity)) {
    // 是base64直接下载
    const data = base64ToBuffer(tableSetting.rowClickObj.RM_Entity);
    saveAs(data, tableSetting.rowClickObj.RM_FileName);
  } else {
    // 不是base64先转换下载
    const base64 = arrayToBase64(tableSetting.rowClickObj.RM_Entity);
    const data = base64ToBuffer(base64);
    saveAs(data, tableSetting.rowClickObj.RM_FileName);
  }
};
// 点击确认事件
const handleOK = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      const {
        Columns,
        Rows,
        IsBlankLine,
        ResolveContext,
        Resolve,
        IsPaging,
        DataSource,
        OrderBy,
        SQL,
        Orientation,
        VerticalGroup,
        TableName
      } = formData.value;
      const Config = `{"Columns":${Columns},"Rows":${Rows},"IsBlankLine":${IsBlankLine ? 1 : 0},"Resolve":${
        Resolve ? 1 : 0
      },"ResolveContext": "${ResolveContext || ""}","VerticalGroup": ${VerticalGroup ? 1 : 0},"IsPaging":${
        IsPaging ? 1 : 0
      },"DataSource":"${DataSource}","OrderBy":"${
        OrderBy ? OrderBy.replace(/"/g, '\\"') : "" || ""
      }","Orientation":"${Orientation}","SQL":"${SQL || ""}","TableName":"${TableName || ""}"}`;
      if (modalSetting.type == 1) {
        const params = {
          rM_ID: proxy.$global.createID(),
          fmT_ID: parentData.value.FMT_ID,
          rM_FileName: formData.value.RM_FileName,
          rM_FileSize: formData.value.RM_FileSize,
          rM_Entity: formData.value.RM_Entity,
          rM_Enabled: formData.value.RM_Enabled,
          rM_Index: formData.value.RM_Index,
          rM_IsFront: formData.value.RM_IsFront,
          rM_FileTime: new Date(),
          rM_Config: Config
        };
        proxy.$vueAxios.post("Master_Base_ReportModule", params).then(() => {
          modalSetting.visible = false;
          getTableData(parentData.value);
        });
      } else if (modalSetting.type == 2) {
        const params = {
          rM_ID: tableSetting.rowClickObj.RM_ID,
          fmT_ID: tableSetting.rowClickObj.FMT_ID,
          rM_FileName: formData.value.RM_FileName,
          rM_FileSize: formData.value.RM_FileSize,
          rM_Entity: formData.value.RM_Entity,
          rM_Enabled: formData.value.RM_Enabled,
          rM_Index: formData.value.RM_Index,
          rM_IsFront: formData.value.RM_IsFront,
          rM_FileTime: new Date(),
          rM_Config: Config
        };
        proxy.$vueAxios.put("Master_Base_ReportModule", params).then(() => {
          modalSetting.visible = false;
          getTableData(parentData.value);
        });
      }
    }
  });
};
// 获取文件信息
const uploadChange = (file: any) => {
  formData.value.RM_FileName = file.name;
  formData.value.RM_FileSize = file.size;
  fileToBase64(file.raw, (res: any) => {
    base64ToBlob(res, (res2: string) => {
      formData.value.RM_Entity = res2;
    });
  });
};

// 将getTableData函数暴露给父组件
defineExpose({ getTableData });
</script>

<style scoped lang="scss">
.form-tab6 {
  height: calc(100% - 40px);
  .button-group {
    margin: 0 0 10px;
  }
}
</style>
